package com.camera2.http;

import android.content.Context;
import android.util.Log;
import com.camera2.Utils.StreamUtils;
import com.camera2.local.SharedPrefer;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Login {

	public static String login(Context context, String username, String password)
			throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(GlobalUrl.getLoginUrl());
		httpPost.addHeader("Content-Type", "application/json");
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("mobile", username);
		jsonParam.put("password", password);

		StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		 httpPost.setEntity(entity);

		HttpResponse response = client.execute(httpPost);
		int code = response.getStatusLine().getStatusCode();
		InputStream is = response.getEntity().getContent();
		String result = StreamUtils.readStream(is);
		Log.i("Login", "login: "+result);
		JSONObject jsonObj = new JSONObject(result);
		String msg = jsonObj.getString("msg");
		if (msg.equals("success")) {
			String token = jsonObj.getString("token");
			String name = jsonObj.getString("name");
			SharedPrefer.SaveToken(context, token);
			SharedPrefer.SaveUsername(context, name);
		} 
		return msg;
	}
}
